import mergeWith from "lodash/mergeWith";
import isArray from "lodash/isArray";
import cloneDeep from "lodash/cloneDeep";

export const MUTATION_UPDATE_USER_INFO = "updateUserInfo";
export const MUTATION_LOGOUT = "user-logout";

const DEFAULT_INFO = {
    userId: -1,
    userName: "游客",
    headPortrait: "600fcd4eeaf71d41bb4f4850",
    realName: "游客",
    sex: 1,
    phone: "***",
    email: "***",
    roleId: 1,
    roleInfoEntity: {
        id: -1,
        platformId: 0,
        unitId: 0,
        tailingPondId: 0,
        roleName: "游客",
        description: "",
    },
    authorizationEntityList: []
}

const state = {
    userInfo: {
        userId: -1,
        userName: "游客",
        headPortrait: "600fcd4eeaf71d41bb4f4850",
        realName: "游客",
        sex: 1,
        phone: "***",
        email: "***",
        roleId: 1,
        roleInfoEntity: {
            id: -1,
            platformId: 0,
            unitId: 0,
            tailingPondId: 0,
            roleName: "游客",
            description: "",
        },
        authorizationEntityList: []
    },
    hasLogin: false,
};

const mutations = {
    [MUTATION_UPDATE_USER_INFO](state,payload){
        const userInfo = payload.userInfo;
        if(!userInfo) {
            throw new Error("用户信息不足。");
        }
        mergeWith(state.userInfo, userInfo, (objValue, srcValue) => {
            if (isArray(objValue)) return srcValue;
            return undefined;
        });
        state.hasLogin = Boolean(payload.loginSuccess);
    },
    [MUTATION_LOGOUT](state){
        mergeWith(state.userInfo, cloneDeep(DEFAULT_INFO), (objValue, srcValue) => {
            if (isArray(objValue)) return srcValue;
            return undefined;
        });
        state.hasLogin = false;
    }
};

export default {
    state,
    mutations
}
